package com.zhxxfwzx.security;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhxxfwzx.common.lang.RespBean;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @Description TODO
 * @title: LoginFailureHandler
 * @Author LiJing
 * @Date: 2021/6/161:04 下午
 * @Version 1.0
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = response.getWriter();
        RespBean error = RespBean.error(exception.getMessage());
        if (exception instanceof LockedException){
            error.setMsg("账户被锁定，请联系管理员!");
        }else if (exception instanceof CredentialsExpiredException) {
            error.setMsg("密码过期，请联系管理员!");
        } else if (exception instanceof AccountExpiredException) {
            error.setMsg("账户过期，请联系管理员!");
        } else if (exception instanceof DisabledException) {
            error.setMsg("账户被禁用，请联系管理员!");
        } else if (exception instanceof BadCredentialsException) {
            error.setMsg("用户名或者密码输入错误，请重新输入!");
        }
        out.write(new ObjectMapper().writeValueAsString(error));
        out.flush();
        out.close();
    }
}
